package com.abai.doubi.utils;


import cn.hutool.core.io.IoUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
@Data
@AllArgsConstructor
@Slf4j
public class QiniuKodoUtil {

    private static final String qiniu_ak = "your-qiniu-access-key";
    private static final String qiniu_sk = "your-qiniu-secret-key";
    private static final String BUCKET = "your-qiniu-bucket-name";
    //域名、测试域名
    private static final String DOMAIN = "your-qiniu-domain";

    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public static String upload(byte[] bytes, String objectName) {
        //构造一个带指定 Region 对象的配置类
        Zone zone = Zone.zone2();
        Configuration cfg = new Configuration(zone);
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = objectName;

        Auth auth = Auth.create(qiniu_ak, qiniu_sk);
        String upToken = auth.uploadToken(BUCKET);

        String url = "http://" + DOMAIN + "/" + key;
        try {
            //响应数据
            Response response = uploadManager.put(new ByteArrayInputStream(bytes),key,upToken,null, null);
            //解析上传成功的<<结果>>
            //DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

            //文件名
            //System.out.println(putRet.key);

            //ETag
            //System.out.println(putRet.hash);

        } catch (QiniuException ex) {
            ex.printStackTrace();
            if (ex.response != null) {
                System.err.println(ex.response);
                try {
                    String body = ex.response.toString();
                    System.err.println(body);
                } catch (Exception ignored) {
                }
            }
        }
        log.info("文件上传到:{}", url);
        return url;
    }

//    public static void main(String[] args) throws FileNotFoundException {
//        byte[] bytes = IoUtil.readBytes(new FileInputStream("tts_test.wav"), true);
//        upload(bytes,"tts_test.wav");
//    }

    //调用七牛云语音合成接口废代码
    //            // 修改 sendVoiceMessage 方法中的请求体构建部分
//            Map<String, Object> requestBody = new HashMap<>();
//            requestBody.put("content", reply);
//            requestBody.put("spkid", 7); // 设置默认发音人
//            requestBody.put("audioType", 3); // 设置默认音频类型
//            requestBody.put("volume", 1.0); // 设置默认音量
//            requestBody.put("speed", 1.0); // 设置默认语速
//
//            String jsonStr = JSONUtil.toJsonStr(requestBody);
//            String qiniuToken = generateQiniuTokenV2("POST", "https://ap-gate-z0.qiniuapi.com/voice/v2/tts", "application/json", jsonStr);
//            // 文字转语音
//            okhttp3.RequestBody body = okhttp3.RequestBody.create(
//                    MediaType.parse("application/json"),
//                    jsonStr
//            );
//            // 构建请求
//            Request request = new Request.Builder()
//                    .url("https://ap-gate-z0.qiniuapi.com/voice/v2/tts")
//                    .post(body)
//                    .addHeader("Authorization",qiniuToken)
//                    .build();
//            // 发送请求并处理响应
//            Response voiceResponse = okHttpClient.newCall(request).execute();
//            if (!voiceResponse.isSuccessful()) {
//                return Result.error("语音合成失败: " + voiceResponse.body().string());
//            }
//            JSONObject responseBody = JSONUtil.parseObj(voiceResponse.body().string());
//            String audioUrl = responseBody.getJSONObject("result").getStr("audioUrl");


    //    private static final String qiniu_ak = "rcqOhfYhMlwULpTMST_chmvjgW72ykyUlge_4mJo";
//    private static final String qiniu_sk = "jpgZ7GWVGzwc3zRaxQOmJ9k6M6w_Kym3nVmlM2d8";
//    public String generateQiniuToken(String method, String url, String contentType, String bodyStr) {
//
//        try {
//            // 解析URL
//            URL parsedUrl = new URL(url);
//            String host = parsedUrl.getHost();
//            String path = parsedUrl.getPath();
//            String rawQuery = parsedUrl.getQuery();
//
//            // 构造待签名的data字符串
//            StringBuilder dataBuilder = new StringBuilder();
//            dataBuilder.append(method.toUpperCase()).append(" ").append(path);
//
//            // 添加查询参数
//            if (StrUtil.isNotBlank(rawQuery)) {
//                dataBuilder.append("?").append(rawQuery);
//            }
//
//            // 添加Host
//            dataBuilder.append("\nHost: ").append(host);
//
//            // 添加Content-Type（如果存在）
//            if (StrUtil.isNotBlank(contentType)) {
//                dataBuilder.append("\nContent-Type: ").append(contentType);
//            }
//
//            // 添加空行
//            dataBuilder.append("\n\n");
//
//            // 添加body（根据条件判断）
//            if (StrUtil.isNotBlank(bodyStr) &&
//                    StrUtil.isNotBlank(contentType) &&
//                    !"application/octet-stream".equals(contentType)) {
//                dataBuilder.append(bodyStr);
//            }
//
//            String data = dataBuilder.toString();
//
//            // 计算HMAC-SHA1签名
//            Mac mac = Mac.getInstance("HmacSHA1");
//            SecretKeySpec secretKeySpec = new SecretKeySpec(qiniu_sk.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
//            mac.init(secretKeySpec);
//            byte[] signBytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
//
//            // URL安全的Base64编码
//            String encodedSign = Base64.encodeUrlSafe(signBytes);
//
//            // 拼接最终的Token
//            return "Qiniu " + qiniu_ak + ":" + encodedSign;
//
//        } catch (Exception e) {
//            throw new RuntimeException("生成七牛云签名失败", e);
//        }
//    }
//
//    public String generateQiniuTokenV2(String method, String url, String contentType, String bodyStr) {
//        Auth auth = Auth.create(qiniu_ak,qiniu_sk);
//        String token = auth.signQiniuAuthorization(url, method, bodyStr.getBytes(), "application/json");
//        return "Qiniu " + token;
//    }
}

